package com.nervenets.web.controller.handler.user.wealth;

import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.hibernate.domain.user.WealthFlow;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class UserWealthFlowsHandler extends Handler<UserWealthFlowsParams> {
    @Override
    public String handle(UserWealthFlowsParams params, HttpServletRequest request) throws Exception {
        String hql = "from WealthFlow where userId = ? ";
        List<Object> objects = new ArrayList<>();
        objects.add(params.getUserId());

        if (params.getStartTime() > 0 && params.getEndTime() > 0 && params.getEndTime() > params.getStartTime()) {
            hql += "and createTime between ? and ? ";
            objects.add(params.getStartTime());
            objects.add(params.getEndTime());
        }
        BigDecimal income = BigDecimal.ZERO;
        BigDecimal outlay = BigDecimal.ZERO;

        if (params.getStart() == 0) {
            income = userDao.getSumOfByHql(hql + "and offset > 0 ", "offset", objects);
            outlay = userDao.getSumOfByHql(hql + "and offset < 0 ", "offset", objects);
        }

        if (null != params.getOperateType()) {
            hql += "and operateType = ? ";
            objects.add(params.getOperateType());
        }

        if (null != params.getWealthType()) {
            hql += "and wealthType = ? ";
            objects.add(params.getWealthType());
        }

        hql += "order by id desc ";

        List<WealthFlow> flows = userDao.getAllObjectsByHql(hql, objects, params.getStart(), params.getLimit());
        return successMessage(
                flows,
                new KeyValue("income", income),
                new KeyValue("outlay", outlay)
        );
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
